package cn.wen.core.refresh.creator;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;

import cn.wen.core.R;


/**
 * Created by Darren on 2017/1/3.
 * Email: 240336124@qq.com
 * Description: 默认样式的刷新头部辅助类
 * 如淘宝、京东、不同的样式可以自己去实现
 */

public class DefaultRefreshCreator extends RefreshViewCreator {
    // 加载数据的ImageView
    private View mRefreshIv;
    private ObjectAnimator mAnimator;
    private View mRefreshView;


    @Override
    public View getRefreshView(Context context, ViewGroup parent) {
        mRefreshView = LayoutInflater
                .from(context)
                .inflate(R.layout.refresh_header_view, parent, false);
        mRefreshIv = mRefreshView.findViewById(R.id.refresh_iv);
        return mRefreshView;
    }

    @Override
    public void onPull(int currentDragHeight, int refreshViewHeight, int currentRefreshStatus) {
        float rotate = ((float) currentDragHeight) / refreshViewHeight;// 0-1 >1
        // 不断下拉的过程中旋转图片
        if (rotate<0){
           rotate=0;
        }else if (rotate>1){
            rotate=1;
        }
        mRefreshIv.setRotation(rotate * 360);
        mRefreshIv.setScaleX(rotate);
        mRefreshIv.setScaleY(rotate);
    }

    @Override
    public void onRefreshing() {
        // 刷新的时候不断旋转
        mRefreshIv.setPivotX(mRefreshIv.getWidth()/2);//设置指定旋转中心点X坐标
        mRefreshIv.setPivotY(mRefreshIv.getHeight()/2);//设置指定旋转中心点X坐标
        mAnimator = ObjectAnimator.ofFloat(mRefreshIv, "rotation", 0, 360);
        mAnimator.setDuration(500);
        mAnimator.setInterpolator(new LinearInterpolator());
        mAnimator.setRepeatCount(-1);
        mAnimator.setRepeatMode(ObjectAnimator.RESTART);
        mAnimator.start();
    }

    @Override
    public void onStopRefresh() {
        // 停止加载的时候清除动画
        if(mAnimator !=null){
            mAnimator.cancel();
        }
        if (mRefreshIv!=null){
            mRefreshIv.setRotation(0);
            mRefreshIv.clearAnimation();
        }

    }

    @Override
    public int getMeasuredHeight() {
        return mRefreshView.getMeasuredHeight();
    }
}
